package com.keur.money.ui.splash.act

import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.keur.money.R
import com.keur.money.base.utils.ImageUtil
import com.keur.money.base.utils.helper.ActivityStackManager
import com.keur.money.config.KeurConfigs
import com.keur.money.databinding.ActMullaSplashBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpAct
import com.keur.money.ui.main.act.KeurMainAct
import com.keur.money.ui.splash.impl.KeurSplashPresenterImpl
import com.keur.money.ui.splash.view.IKeurSplashView
import com.keur.money.ui.user.act.KeurUserLoginAct
import com.keur.money.utils.dialog.AppUpdateDialog
import com.keur.money.utils.dialog.LanguageDialog
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurAnalysisHelper
import com.keur.money.utils.helper.KeurAppUpdateHelper
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.helper.SharedHelper
import com.keur.money.utils.language.LocaleContract
import com.keur.money.utils.language.MultiLanguages
import java.util.Locale
import java.util.TimeZone


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/24 11:03
 * @Annotation：启动页面
 */
class KeurSplashAct : MvpAct<IKeurSplashView, KeurSplashPresenterImpl>(), IKeurSplashView {
    lateinit var binding: ActMullaSplashBinding
    private var updateHelper: KeurAppUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // TODO: 更新成功，进入主界面
            showKeurIntentAction()
        } else {
            // 1、用户取消或失败，不处理，继续进入主界面
            // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
            if (updateHelper == null) {
                showKeurIntentAction()
                return@registerForActivityResult
            }
            updateHelper?.handleNoUpdate {
                showKeurIntentAction()
            }
        }
    }

    override fun createPresenter(): KeurSplashPresenterImpl {
        return KeurSplashPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaSplashBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        //关闭所有页面
        ActivityStackManager.finishAllActivity(KeurSplashAct::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_DIALOG_NOTICE_NUM, 0)
    }

    override fun initMullaListener() {
    }

    override fun initMullaData() {
        showMullaLoading(isTOuchOut = false, isCancel = true)
        presenter.loadMullaTimeZoneAction()

        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null) {
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE
            ImageUtil.instance?.loadImageUrl(this, binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /**
     * 显示选择语言
     */
    private fun showMullaLanguageDialog() {
        val languageDialog = LanguageDialog(this, "Launch Page", object : LanguageDialog.IDialogCallback {
                override fun settingLanguageEnglish() {
                    saveSelectLanguageAction(LocaleContract.getEnglishLocale())
                }

                override fun settingLanguageSwahili() {
                    saveSelectLanguageAction(LocaleContract.getSwahiliLocale())
                }
            })
        languageDialog.setCancelable(false)
        languageDialog.setCanceledOnTouchOutside(false)
        languageDialog.show()
    }

    /**
     * 设置语言
     */
    private fun saveSelectLanguageAction(newLocale: Locale) {
        //是否需要重启
        val restart = MultiLanguages.setAppLanguage(this@KeurSplashAct, newLocale)
        if (restart) {
            // 我们可以充分运用 Activity 跳转动画，在跳转的时候设置一个渐变的效果
            onIntent(KeurSplashAct::class.java)
            overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
            finish()
        } else {
            showMullaLoading(isTOuchOut = false, isCancel = true)
            presenter.loadMullaCommonConfigAction()
        }
    }

    /**
     * 获取地区转发成功
     */
    override fun showMullaTimeZoneRequestData(dataString: String) {
        var timeZone = ""
        var zoneCode = ""
        var zoneCountry = ""

        dataString.split(",").apply {
            if (this.isNotEmpty()) {
                timeZone = this[0].trim()
            }
            if (this.size >= 2) {
                zoneCode = this[1].trim()
            }
            if (this.size >= 3) {
                zoneCountry = this[2].trim()
            }
        }
        //保存转发地区
        SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_TIMEZONE, timeZone)
        //保存转发地区 区号
        SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_TIMEZONE_CODE, zoneCode)
        //保存国家标识
        SharedHelper.saveKeurSPData(SharedHelper.KEUR_SPKEY.KEUR_TIMEZONE_COUNTRY, zoneCountry)

        //初始化analysis lib 赋值 转发地区
        KeurAnalysisHelper.initAnalysisLibAtZoneSuccess()

        //是否是坦桑地区
        if (KeurConfigs.isTanz()) {
            if (!SharedHelper.getKeurSPBoolean(SharedHelper.KEUR_SPKEY.KEUR_LANGUAGE_LAUNCH)) {
                hideMullaLoading()
                showMullaLanguageDialog()
            } else {
                presenter.loadMullaCommonConfigAction()
            }
        } else {
            presenter.loadMullaCommonConfigAction()
        }

        //添加埋点
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_LAUNCH_START)
    }

    /**
     * 客服配置获取成功
     */
    override fun showKeurLoadConfigSuccess() {
        //是否强制更新版本
        val isUpdate = KeurCustomConfigsHelper.isKeurAppUpdateMust()
        if (isUpdate){
            showKeurAppUpdateDialog()
            return
        }
        showKeurIntentAction()
    }

    /**
     * 跳转到首页 || 登录页
     */
    private fun showKeurIntentAction(){
        // TODO: 2025/05/26 - 2025/05/30更新，权限改到首页点申贷判断
        //已登录 - 进入主页
        if (SharedHelper.getKeurSPBoolean(SharedHelper.KEUR_SPKEY.KEUR_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            KeurAnalysisHelper.initAnalysisLibAtLoginSuccess()
            showKeurMainPage()
        } else {//进入登录页
            showKeurLoginPage()
        }
    }

    /**
     * 进入登录页
     */
    private fun showKeurLoginPage() {
        onIntent(KeurUserLoginAct::class.java)
        finish()
    }

    /**
     * 进入首页
     */
    private fun showKeurMainPage() {
        //保存的时区和当前时区不一致，需要进入登录页面
        if (TimeZone.getDefault().id != SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_TIMEZONE_ID)){
            showKeurLoginPage()
            return
        }
        onIntent(KeurMainAct::class.java)
        finish()
    }

    /**
     * 版本更新Dialog
     */
    private fun showKeurAppUpdateDialog(){
        val updateDialog = AppUpdateDialog(this,"Launch page",object : AppUpdateDialog.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = KeurAppUpdateHelper(this@KeurSplashAct, true, updateLauncher)
                    }
                    updateHelper?.checkAndStartUpdate { showKeurIntentAction() }
                } catch (e: Exception) {
                    showKeurIntentAction()
                }
            }
        })
        updateDialog.show()
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.resumeIfInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_LAUNCH_END)
    }
}